<template>
	<view class="container">
		<!-- 可提现金额展示 -->
		<view class="balance-card">
			<view class="balance-info">
				<text class="balance-label">可提现金额</text>
				<text class="balance-amount">¥{{ userInfo.balance || '0.00' }}</text>
			</view>
			<view class="daily-limit-info">
				<view class="limit-item">
					<text class="limit-label">今日已提现：</text>
					<text class="limit-value">¥{{ todayWithdrawTotal }}</text>
				</view>
				<view class="limit-item">
					<text class="limit-label">今日剩余额度：</text>
					<text class="limit-value">¥{{ remainingDailyAmount }}</text>
				</view>
			</view>
		</view>

		<!-- 提现操作区域 -->
		<view class="withdraw-section">
			<view class="section-title">提现申请</view>
			<view class="withdraw-form">
				<view class="form-item">
					<text class="form-label">到账金额</text>
					<view class="input-wrapper">
						<u-input type="digit" class="withdraw-input" placeholder="请输入到账金额" v-model="withdrawAmount"
							@input="onAmountInput" />
						<text class="currency">元</text>
					</view>
				</view>
				
				<!-- 手续费显示 -->
				<view v-if="withdrawAmount && parseFloat(withdrawAmount) > 0" class="fee-display">
					<view class="fee-item">
						<text class="fee-label">到账金额：</text>
						<text class="fee-value">¥{{ withdrawAmount }}</text>
					</view>
					<view class="fee-item">
						<text class="fee-label">手续费：</text>
						<text class="fee-value">¥{{ calculatedFee }}</text>
					</view>
					<view class="fee-item total">
						<text class="fee-label">合计扣款：</text>
						<text class="fee-value">¥{{ totalDeduction }}</text>
					</view>
				</view>
				
				<view class="quick-amount">
					<text class="quick-label">快捷到账金额：</text>
					<view class="quick-buttons">
						<text class="quick-btn" v-for="amount in quickAmounts" :key="amount"
							@click="selectQuickAmount(amount)" :class="[withdrawAmount == amount ? 'active' : '']">
							{{ amount }}元
						</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 提现规则 -->
		<view class="rules-section">
			<view class="section-title">提现规则</view>
			<view class="rules-content">
				<text class="rule-item">• 到账金额将在1-3个工作日内到账</text>
				<text class="rule-item">• 最小到账金额：0.1元</text>
				<text class="rule-item">• 单次最大到账金额：200元</text>
				<text class="rule-item">• 每日最大到账总额：2000元</text>
				<text class="rule-item" v-if="feeRatio > 0">• 提现手续费：{{ feeRatio * 100 }}%（最低0.01元）</text>
			</view>
		</view>

		<!-- 提现按钮 -->
		<view class="withdraw-btn-wrapper">
			<ZButton class="withdraw-btn" :disabled="!canWithdraw" @click="submitWithdraw" :text="withdrawBtnText">
			</ZButton>
		</view>

		<!-- 提现记录 -->
		<view class="records-section">
			<view class="section-title">提现记录</view>
			<view v-if="withdrawRecords.length > 0" class="records-list">
				<view class="record-item" v-for="record in withdrawRecords" :key="record.id">
					<view class="record-left">
						<text class="record-amount">¥{{ Math.abs(record.amount) }}</text>
						<text class="record-time">{{ record.create_time }}</text>
					</view>
					<view class="record-right">
						<text v-if="record.status !== 0" class="record-status" :class="[getStatusClass(record.status)]">
							{{ getStatusText(record.status) }}
						</text>
						<!-- 状态为-1时显示重新提现按钮 -->
						<view v-if="record.status === 0" class="retry-withdraw">
							<view class="retry-btn" :class="{ 'disabled': !canRetryWithdraw }" @click="retryWithdraw(record)">
								<text class="retry-text">{{ isPolling ? '处理中...' : '重新提现' }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="empty-records">
				<u-empty text="暂无提现记录" mode="data"></u-empty>
			</view>
		</view>
	</view>
</template>

<script>
import ZButton from '@/components/ZButton.vue'
export default {
	components: {
		ZButton
	},
	data() {
		return {
			withdrawAmount: '',
			quickAmounts: [10, 50, 100, 200],
			withdrawRecords: [],
			loading: false,
			pageNo: 1,
			pageSize: 10,
			hasMore: true,
			todayWithdrawTotal: 0, // 当日已提现总金额
			dailyLimit: 2000, // 每日提现限额
			feeRatio: 0,
			pollingTimer: null, // 轮询定时器
			isPolling: false // 是否正在轮询
		}
	},
	computed: {
		// 是否可以提现
		canWithdraw() {
			if (!this.withdrawAmount) return false
			const amount = parseFloat(this.withdrawAmount)
			if (isNaN(amount)) return false
			if (amount < 0.1) return false
			
			// 检查余额：提现金额 + 手续费 <= 用户余额
			const totalDeduction = parseFloat(this.totalDeduction)
			if (totalDeduction > parseFloat(this.userInfo.balance || 0)) return false
			
			// 检查每日限额：按到账金额计算
			if (this.todayWithdrawTotal + amount > this.dailyLimit) return false
			return true
		},

		// 提现按钮文本
		withdrawBtnText() {
			if (!this.withdrawAmount) return '请输入到账金额'
			const amount = parseFloat(this.withdrawAmount)
			if (isNaN(amount)) return '请输入有效金额'
			if (amount < 0.1) return '最小到账金额0.1元'
			
			// 检查余额：到账金额 + 手续费 <= 用户余额
			const totalDeduction = parseFloat(this.totalDeduction)
			if (totalDeduction > parseFloat(this.userInfo.balance || 0)) return '余额不足'
			
			if (this.todayWithdrawTotal + amount > this.dailyLimit) return `今日提现额度不足`
			return `提现 ¥${amount}`
		},

		// 今日剩余可提现金额
		remainingDailyAmount() {
			return Math.max(0, this.dailyLimit - this.todayWithdrawTotal)
		},

		// 是否有处理中的提现
		hasPendingWithdraw() {
			return this.withdrawRecords.some(record => record.status === 0)
		},

		// 是否可以重新提现（轮询期间禁用）
		canRetryWithdraw() {
			return !this.isPolling
		},

		// 计算手续费
		calculatedFee() {
			if (!this.withdrawAmount) return '0.00'
			const amount = parseFloat(this.withdrawAmount)
			if (isNaN(amount) || amount <= 0) return '0.00'
			
			// 计算手续费，最低0.01元
			let fee = amount * this.feeRatio
			fee = Math.max(fee, 0.01) // 最低手续费0.01元
			
			return fee.toFixed(2)
		},

		// 合计扣款金额（到账金额 + 手续费）
		totalDeduction() {
			if (!this.withdrawAmount) return '0.00'
			const amount = parseFloat(this.withdrawAmount)
			const fee = parseFloat(this.calculatedFee)
			
			if (isNaN(amount) || amount <= 0) return '0.00'
			
			const total = amount + fee
			return total.toFixed(2)
		}
	},
	onLoad() {
		this.$api.getConfigByKey('fee_ratio').then(res => {
			this.feeRatio = parseFloat(res.value || 0)
		})
		this.getWithdrawRecords()
		this.getTodayWithdrawTotal()
	},
	onUnload() {
		// 页面卸载时清理定时器
		this.clearPollingTimer()
	},
	methods: {
		// 输入金额处理
		onAmountInput(e) {
			let value = e.detail.value
			// 限制最多两位小数
			if (value.includes('.')) {
				const parts = value.split('.')
				if (parts[1] && parts[1].length > 2) {
					value = parts[0] + '.' + parts[1].substring(0, 2)
				}
			}
			this.withdrawAmount = value
		},

		// 选择快捷金额
		selectQuickAmount(amount) {
			this.withdrawAmount = amount.toString()
		},

		// 选择全部金额
		selectAllAmount() {
			const balance = parseFloat(this.userInfo.balance || 0)
			const remainingAmount = this.remainingDailyAmount
			// 取余额和剩余额度中的较小值
			this.withdrawAmount = Math.min(balance, remainingAmount).toFixed(2)
		},

		// 提交提现
		async submitWithdraw() {
			if (!this.canWithdraw) return

			// 检查是否有处理中的提现
			if (this.hasPendingWithdraw) {
				uni.showModal({
					title: '提示',
					content: '您有提现中的金额，请处理完成后再提交新的提现申请。',
					showCancel: false,
					confirmText: '我知道了'
				})
				return
			}

			const amount = parseFloat(this.withdrawAmount)

			try {
				uni.showLoading({ title: '提交中...' })

				// 调用提现接口
				const res = await this.$api.createWithdraw({
					amount: amount,
					user_id: this.userInfo.id
				})

				uni.hideLoading()
				this.openWithdrawPage(res)

			} catch (error) {
				console.log(error)
			}
		},

		// 处理提现成功
		handleWithdrawSuccess() {
			// 清空输入
			this.withdrawAmount = ''

			// 刷新提现记录和用户信息
			this.getWithdrawRecords()
			this.getTodayWithdrawTotal()
			this.$store.dispatch('getUserInfo')
		},

		// 获取今日提现总金额
		async getTodayWithdrawTotal() {
			try {
				const today = new Date()
				const startDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`

				const res = await this.$api.getTodayWithdrawTotal({
					user_id: this.userInfo.id,
					date: startDate
				})

				this.todayWithdrawTotal = res.total || 0

			} catch (error) {
				console.error('获取今日提现总金额失败:', error)
				this.todayWithdrawTotal = 0
			}
		},

		// 获取提现记录
		async getWithdrawRecords() {
			if (this.loading) return
			this.loading = true

			try {
				const res = await this.$api.getBalanceRecordList({
					user_id: this.userInfo.id,
					type: 1 // 1表示提现
				})

				// 按照状态排序：status=0（提现中）、status=1（提现成功）、status=-1（提现失败）
				this.withdrawRecords = (res || []).sort((a, b) => {
					// 定义状态优先级：0 > 1 > -1
					const statusPriority = { 0: 3, 1: 2, '-1': 1 }
					const priorityA = statusPriority[a.status] || 0
					const priorityB = statusPriority[b.status] || 0

					// 如果状态优先级相同，按创建时间倒序排列
					if (priorityA === priorityB) {
						return new Date(b.create_time) - new Date(a.create_time)
					}

					return priorityB - priorityA
				})

				this.hasMore = false

			} catch (error) {
				console.error('获取提现记录失败:', error)
				uni.showToast({
					title: '获取提现记录失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 获取状态样式类
		getStatusClass(status) {
			// 根据实际业务状态返回对应样式
			// 状态：0-提现中，1-提现成功，-1-提现失败
			switch (status) {
				case 0: return 'status-pending'
				case 1: return 'status-success'
				case -1: return 'status-failed'
				default: return 'status-pending'
			}
		},

		// 获取状态文本
		getStatusText(status) {
			switch (status) {
				case 0: return '提现中'
				case 1: return '提现成功'
				case -1: return '提现失败'
				default: return '处理中'
			}
		},

		// 重新提现
		retryWithdraw(record) {
			if (!this.canRetryWithdraw) return
			uni.showLoading({ title: '提交中...' })

			// 调用重新提现接口
			this.$api.retryWithdraw({
				id: record.id
			}).then(res => {
				this.openWithdrawPage(res)
			})
		},

		// 打开提现页面
		openWithdrawPage(res) {
			// 检查是否支持小程序提现确认功能
			if (wx.canIUse('requestMerchantTransfer')) {
				// 检查返回数据中是否包含必要字段
				if (!res.package) {
					uni.showToast({
						title: '提现接口返回数据缺少package字段',
					})
					return
				}

				// 唤醒小程序提现确认
				wx.requestMerchantTransfer({
					mchId: res.mchId, // 使用后端返回的商户号
					appId: res.appId,
					package: res.package, // 使用后端返回的package
					success: (transferRes) => {
						// 提现确认成功
						console.log('提现确认成功:', transferRes);
						uni.showToast({
							title: '提现申请已提交',
							icon: 'success'
						})
						// 开始轮询
						this.startPolling()
					},
					fail: (transferRes) => {
						console.log('提现确认失败:', transferRes);
						if (transferRes.result === 'cancel') {
							uni.showToast({
								title: '提现申请已取消',
							})
							return
						}
						// 即使确认失败，提现申请也已提交到微信
						uni.showToast({
							title: transferRes.errMsg
						})
						this.handleWithdrawSuccess()
					}
				});
			} else {
				// 微信版本过低
				wx.showModal({
					content: '你的微信版本过低，请更新至最新版本后再尝试提现。',
					showCancel: false,
					success: () => {
					// 即使版本过低，提现申请也已提交，显示成功
					uni.showToast({
						title: '提现申请已提交',
						icon: 'success'
					})
					// 开始轮询
					this.startPolling()
					}
				});
			}
		},

		// 开始轮询
		startPolling() {
			this.isPolling = true
			this.pollingTimer = setInterval(() => {
				this.pollWithdrawStatus()
			}, 1000) // 每秒轮询一次
		},

		// 轮询提现状态
		async pollWithdrawStatus() {
			try {
				// 重新获取提现记录
				await this.getWithdrawRecords()
				
				// 检查是否还有处理中的提现
				const hasPending = this.withdrawRecords.some(record => record.status === 0)
				
				if (!hasPending) {
					// 没有处理中的提现，停止轮询
					this.stopPolling()
					// 刷新用户信息和今日提现总额
					this.getTodayWithdrawTotal()
					this.$store.dispatch('getUserInfo')
					// 清空输入
					this.withdrawAmount = ''
				}
			} catch (error) {
				console.error('轮询提现状态失败:', error)
			}
		},

		// 停止轮询
		stopPolling() {
			this.isPolling = false
			if (this.pollingTimer) {
				clearInterval(this.pollingTimer)
				this.pollingTimer = null
			}
		},

		// 清理定时器
		clearPollingTimer() {
			this.stopPolling()
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background: #F8F9FA;
	height: 100%;
	overflow: hidden;
}

.container {
	height: 100%;
	padding: 20rpx;
	padding-bottom: 150rpx;
}

.balance-card {
	background: linear-gradient(135deg, rgba(255, 67, 67, 1) 0%, rgba(232, 137, 53, 1) 100%);
	border-radius: 20rpx;
	padding: 24rpx 40rpx;

	.balance-info {
		text-align: center;
		color: white;
		margin-bottom: 24rpx;

		.balance-label {
			font-size: 28rpx;
			display: block;
			margin-bottom: 10rpx;
			opacity: 0.9;
		}

		.balance-amount {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
		}
	}

	.daily-limit-info {
		display: flex;
		justify-content: space-between;
		color: white;

		.limit-item {
			flex: 1;
			text-align: center;

			.limit-label {
				font-size: 24rpx;
				opacity: 0.8;
				display: block;
				margin-bottom: 8rpx;
			}

			.limit-value {
				font-size: 32rpx;
				font-weight: bold;
				display: block;
			}
		}
	}
}

.withdraw-section,
.rules-section,
.records-section {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx;
	padding-bottom: 0;

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		position: relative;

		&::before {
			top: 50%;
			transform: translateY(-50%);
			position: absolute;
			content: ' ';
			display: block;
			width: 6rpx;
			border-radius: 6rpx;
			height: 28rpx;
			background: #FF4343;
			left: -20rpx;
		}
	}
}

.withdraw-form {
	.form-item {
		margin-bottom: 30rpx;

		.form-label {
			font-size: 28rpx;
			color: #666;
			display: block;
			margin-bottom: 15rpx;
		}

		.input-wrapper {
			display: flex;
			align-items: center;
			border: 2rpx solid #E5E5E5;
			border-radius: 12rpx;
			padding: 0 20rpx;

			.withdraw-input {
				flex: 1;
				font-size: 32rpx;
				color: #333;
			}

			.currency {
				color: #999;
				font-size: 28rpx;
				margin-left: 10rpx;
			}
		}
	}

	.amount-tips {
		margin-bottom: 30rpx;

		.tip-text {
			display: block;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 8rpx;
		}
	}

	.fee-display {
		background: #F8F9FA;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;

		.fee-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 12rpx;

			&:last-child {
				margin-bottom: 0;
			}

			&.total {
				border-top: 1rpx solid #E5E5E5;
				padding-top: 12rpx;
				margin-top: 8rpx;

				.fee-label {
					font-weight: bold;
					color: #333;
				}

				.fee-value {
					font-weight: bold;
					color: #FF4343;
					font-size: 30rpx;
				}
			}

			.fee-label {
				font-size: 26rpx;
				color: #666;
			}

			.fee-value {
				font-size: 26rpx;
				color: #333;
			}
		}
	}

	.quick-amount {
		.quick-label {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 15rpx;
			display: block;
		}

		.quick-buttons {
			display: flex;
			flex-wrap: wrap;
			gap: 15rpx;

			.quick-btn {
				padding: 15rpx 25rpx;
				background: #F5F5F5;
				border-radius: 12rpx;
				font-size: 26rpx;
				color: #666;

				&.active {
					background: #333;
					color: white;
				}
			}
		}
	}
}

.rules-content {
	.rule-item {
		display: block;
		font-size: 26rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 12rpx;
	}
}

.withdraw-btn-wrapper {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	padding-bottom: 50rpx;
	background: white;
	border-top: 1rpx solid #E5E5E5;
	z-index: 999;
}

.records-list {
	.record-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #F0F0F0;

		&:last-child {
			border-bottom: none;
		}

		.record-left {
			.record-amount {
				font-size: 32rpx;
				font-weight: bold;
				color: #FF6B6B;
				display: block;
				margin-bottom: 8rpx;
			}

			.record-time {
				font-size: 24rpx;
				color: #999;
			}
		}

		.record-right {
			display: flex;
			align-items: center;
			gap: 10rpx;

			.record-status {
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 24rpx;

				&.status-pending {
					background: #FFF2E8;
					color: #FF8F00;
				}

				&.status-success {
					background: #E8F5E8;
					color: #4CAF50;
				}

				&.status-failed {
					background: #FFE8E8;
					color: #F44336;
				}
			}

			.retry-withdraw {
				margin-left: 10rpx;

				.retry-btn {
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 6rpx;
					padding: 12rpx 20rpx;
					background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%);
					border-radius: 20rpx;
					box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
					transition: all 0.3s ease;
					cursor: pointer;

					&:active {
						transform: translateY(2rpx);
						box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.4);
					}

					&.disabled {
						background: #CCCCCC;
						box-shadow: none;
						cursor: not-allowed;
						opacity: 0.6;

						&:active {
							transform: none;
							box-shadow: none;
						}
					}

					.retry-icon {
						font-size: 24rpx;
						color: white;
						font-weight: bold;
						animation: rotate 2s linear infinite;
					}

					.retry-text {
						font-size: 22rpx;
						color: white;
						font-weight: 500;
					}
				}
			}
		}
	}
}

.empty-records {
	padding: 60rpx 0;
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}

	to {
		transform: rotate(360deg);
	}
}
</style>
